package com.hhdys.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hhdys.model.Account;
import com.hhdys.model.Function;
import com.hhdys.model.MenuTree;
import com.hhdys.service.AccountFuncService;
import com.hhdys.service.AccountService;
import com.hhdys.service.FunctionService;
import com.hhdys.service.MenuTreeService;

@Repository
public class DefaultRealm extends AuthorizingRealm {

	private static Logger log = LogManager.getLogger(DefaultRealm.class);
	@Autowired
	private AccountService accountService;
	@Autowired
	private AccountFuncService assService;
	@Autowired
	private FunctionService functionService;
	@Autowired
	private MenuTreeService menuTreeService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection paramPrincipalCollection) {
		log.debug("开始获取权限");
		String username = (String) paramPrincipalCollection
				.getPrimaryPrincipal();
		Account account = accountService.getAccountByUserName(username);
		if (account == null) {
			return null;
		}
		Set<String> role = new HashSet<String>();
		role.add(String.valueOf(account.getRole()));
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(role);
		Set<String> permissions = new HashSet<String>();
		Set<Integer> funcs = assService.getAssByAccountId(account.getId());
		for (int i : funcs) {
			Function function = functionService.getFuncById(i);
			if (function != null) {
				String menuTreeName=menuTreeService.getMenuName(function.getPageId());
				if(StringUtils.isBlank(menuTreeName)){
					continue;
				}
				permissions.add(menuTreeName+ ":"+ function.getName());
			}
		}
		info.setStringPermissions(permissions);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken paramAuthenticationToken)
			throws AuthenticationException {

		String username = (String) paramAuthenticationToken.getPrincipal();
		String pwd = new String(
				(char[]) paramAuthenticationToken.getCredentials());
		Account account = accountService.selAccountByUsernameAndPwd(username,
				pwd);
		if (account != null) {
			return new SimpleAuthenticationInfo(username, pwd, getName());
		}
		return null;
	}

	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

}
